<template>
    <view class="page-wrapper linear-back">
        <view class="finding-box" v-if="devicesList.length == 0">
            <image src="/static/images/help/findingDevice.png" class="image rotate-animation" mode="aspectFill" :draggable="false" />
            <view>{{ $t('pages.addDevice.searchingDeviceText') }} </view>
        </view>

        <view class="result-box" v-if="devicesList.length > 0">
            <view class="desc-text">{{ $t('pages.addDevice.searchResultArr.0') }} {{ devicesList.length }} {{ $t('pages.addDevice.searchResultArr.1') }}</view>
            <view class="result-item" v-for="(item, index) in devicesList" :key="index">
                <image :src="item.image" mode="aspectFill" class="image" @error="setDefaultImage(item)" />
                <view class="info">
                    <view class="bold-text">{{ item.name.slice(0, 10) }}</view>
                    <view class="desc-text">{{ item.deviceId }}</view>
                    <view class="button-wrapper">
                        <up-button :text="$t('pages.addDevice.butnAddDevice')" size="mini" type="primary" shape="circle"
                            class="link-button" @click.stop="addDevice(item.deviceId, item.name, item)"></up-button>
                    </view>
                </view>
            </view>
        </view>

        <view class="bottom-box">
            <up-button :text="$t('pages.addDevice.Rescan')" size="normal" type="primary" @click="refreshDevices" style="width: 620rpx;" shape="circle"></up-button>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, } from 'vue';
import { onLoad, } from '@dcloudio/uni-app';
import { addSheBeiApi } from "@/api/request";
import { CacheUtils, } from '@/utils/index';
import { useI18n } from 'vue-i18n';


const { t } = useI18n();
const devicesList = ref([]);
const deviceTimer = ref(null);
const query = ref({});
const activeDevice = ref({});
const bluetoothMac = ref('');

const setDefaultImage = (deviceItem) => {
    if (deviceItem) {
        deviceItem.image = '/static/deviceType/SKI-050.jpg'
    }
}


const stopscan = () => {
    uni.stopBluetoothDevicesDiscovery({
        success(res) {

        }
    })
};
// 开始搜索设备
const startScan = () => {
    // 先停止扫描，在扫描一次
    devicesList.value = []
    clearInterval(deviceTimer.value);
    uni.showLoading({
        title:  t('pages.addDevice.searchingDevices'),
    });

    uni.startBluetoothDevicesDiscovery({
        success(res) {
            deviceTimer.value = setInterval(() => {
                uni.getBluetoothDevices({
                    success(devices) {
                        devicesList.value = []
                        devices.devices.forEach((device) => {
                            if (device.name &&
								(
									device.name.toLowerCase().includes("ski") || 
									device.name.toLowerCase().includes("stake") ||
									device.name.toLowerCase().includes("af") ||
									device.name.toLowerCase().startsWith("f0") ||
									device.name.toLowerCase().startsWith("f1") ||
									device.name.toLowerCase().startsWith("pf") 
								)
                            ) {
								
                                device.image = `/static/deviceType/${String(device.name).toUpperCase()}.jpg`
                                devicesList.value.push(device);
								// console.log(device)
                                uni.hideLoading();
                            } else {

                            }
                        });
                    },
                    fail(res) {

                    }
                });
            }, 2000);
        },
        fail(err) {
            noneBle();
        },
    });
};

//搜索设备
const initBlue = () => {
    stopscan()
    uni.openBluetoothAdapter({
        success(res) {
            setTimeout(function () {
                startScan();
            }, 1000)

        },
        fail(err) {
            return false;
        },
    });
};

// 安卓初始化
const andriodInit = () => {
    var main = plus.android.runtimeMainActivity();
    var BluetoothAdapter = plus.android.importClass(
        "android.bluetooth.BluetoothAdapter"
    );
    var BAdapter = new BluetoothAdapter.getDefaultAdapter();
    var receiver = plus.android.implements(
        "io.dcloud.android.content.BroadcastReceiver", {
        onReceive: function (context, intent) {
            // 实现 onReceive 回调函数
            plus.android.importClass(intent);
            var action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED == action) {
                var state = intent.getIntExtra(
                    BluetoothAdapter.EXTRA_STATE,
                    BluetoothAdapter.ERROR
                );
                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        break;
                    case BluetoothAdapter.STATE_ON:
                        main.unregisterReceiver(receiver);
                        initBlue();
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        break;
                }
            }
        },
    }
    );
    var IntentFilter = plus.android.importClass("android.content.IntentFilter");
    var filter = new IntentFilter();
    filter.addAction(BAdapter.ACTION_STATE_CHANGED);
    main.registerReceiver(receiver, filter);
    if (!BAdapter.isEnabled()) {
        var enabled = BAdapter.enable(); // 启动蓝牙
        if (!enabled) {
            uni.showModal({
                title: t('pages.addDevice.turnOnBluetoothFail'),
                icon: 'none'
            });
        }
    } else {
        initBlue();
    }
}

// ios初始化
const iosInit = () => {
    // 初始化蓝牙模块
    uni.openBluetoothAdapter({
        success: function () {
            // 获取蓝牙适配器状态
            uni.getBluetoothAdapterState({
                success: function (res) {
                    if (!res.available) {
                        // 蓝牙不可用，提示用户开启
                        uni.showModal({
                            title: t('pages.addDevice.turnOnBluetoothFail'),
                            icon: 'none'
                        });
                    } else {
                        // 蓝牙已开启，执行初始化蓝牙的操作
                        initBlue();
                    }
                },
                fail: function (err) {
                    console.error('Failed to obtain Bluetooth adapter status', err);
                }
            });

            // 监听蓝牙适配器状态变化
            uni.onBluetoothAdapterStateChange(function (res) {
                if (res.available) {
                    // 蓝牙已开启
                    uni.offBluetoothAdapterStateChange(); // 停止监听
                    initBlue();
                }
            });
        },
        fail: function (err) {
            console.error('初始化蓝牙模块失败', err);
            // 可能需要提示用户手动开启蓝牙
            uni.showToast({
                title: t('pages.addDevice.turnOnBluetoothFail'),
                icon: 'none'
            });
        }
    });
}

const refreshIosAdapter = ()=>{
	if (deviceTimer.value) {
		clearInterval(deviceTimer.value);
	}
	// ios设备关闭蓝牙：iOS 系统会缓存已配对或者之前扫描到的蓝牙设备信息，即便设备当前处于断电状态，这些缓存信息仍会被返回。
	// 关闭蓝牙适配器
	uni.closeBluetoothAdapter({
		success: function () {
			console.log('蓝牙适配器已关闭');
			// 重新打开蓝牙适配器
			iosInit();
		},
		fail: function (err) {
			console.error('关闭蓝牙适配器失败:', err);
		}
	});
}

const closeIosAdapter = ()=>{
	// 关闭蓝牙适配器
	uni.closeBluetoothAdapter({
		success: function () {
			console.log('蓝牙适配器已关闭 closeIosAdapter');
		},
		fail: function (err) {
			console.error('关闭蓝牙适配器失败 closeIosAdapter:', err);
		}
	});
}

const refreshDevices = ()=>{
	uni.getSystemInfo({
		success(res) {
			if (res.osName == 'ios') {
				refreshIosAdapter();
			} else {
				andriodInit();
			}
		}
	})
}

const addDevice = async (id, name, item) => {
    clearInterval(deviceTimer.value);
	bluetoothMac.value = id;
    uni.$emit('blelianjie', id, name)
    activeDevice.value = {
        imei: '',
        userid: CacheUtils.get('userid'),
        title: item.name,
        deviceimg: decodeURIComponent( item.image||query.value.deviceimg ),
        dtype: query.value.dtype,
        cptype: query.value.cptype
    }
    uni.showLoading({
        title: t('pages.addDevice.deviceConnecting'),
    });
}

onLoad((options) => {
	console.log(options)
    query.value = options;
});

onMounted(async () => {    
	uni.$emit('bleduankai')
    uni.$on('addimei', (imei) => {
        activeDevice.value.imei = imei
        uni.setStorageSync('shebeiInfo', activeDevice.value)
        clearInterval(deviceTimer.value);
        uni.hideLoading();
        uni.redirectTo({
            url: '/pages/configDevice/wifiHelp'
        })
    })

    uni.getSystemInfo({
        success(res) {
            if (res.osName == 'ios') {
                iosInit();
            } else {
                andriodInit();
            }
        }
    })
})

onUnmounted(() => {
    if (deviceTimer.value) {
        clearInterval(deviceTimer.value);
    }

    uni.hideLoading();
    uni.$off('addimei')
});
</script>

<style lang="scss" scoped>
$bottom-height: 100rpx;

.page-wrapper {
    padding-bottom: $bottom-height;
}

.bottom-box {
    bottom: 0rpx;
    left: 0rpx;
    right: 0rpx;
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: center;
    height: $bottom-height;
    box-sizing: border-box;
    background-color: #FFFFFF;
}

.finding-box {
    margin-top: 240rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    row-gap: 10rpx;
    text-align: center;
    color: #4B5563;

    .image {
        width: 240rpx;
        height: 240rpx;
    }
}

.result-box {
    padding: 0 40rpx;

    .result-item {
        margin-top: 20rpx;
        background-color: #FFFFFF;
        border-radius: 20rpx;
        padding: 20rpx 30rpx;
        display: flex;
        align-items: center;
        column-gap: 20rpx;

        .info {
            flex: 1;
            .button-wrapper{
                display: flex;
                justify-content: flex-end;
            }
            .link-button {
                display: inline-flex;
				align-items: center;
                width: 200rpx;
                margin-top: 30rpx;
                margin-right: 0;
            }
        }

        .image {
            width: 160rpx;
            height: 160rpx;
        }
    }
}

@keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

.rotate-animation {
    transform-origin: center;
    animation: rotate 2.4s linear infinite;
}
</style>